import React, { useState, useEffect } from 'react';
import {
  Box,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Button,
  Chip,
  Paper,
  InputAdornment,
  IconButton,
  Collapse,
} from '@mui/material';
import {
  Search,
  Clear,
  FilterList,
  ExpandMore,
  ExpandLess,
} from '@mui/icons-material';
import { ContentType, OrderBy, ContentQueryParams } from '../../../types';

interface SearchFilterProps {
  onSearch: (params: ContentQueryParams) => void;
  loading?: boolean;
  initialParams?: ContentQueryParams;
}

const SearchFilter: React.FC<SearchFilterProps> = ({
  onSearch,
  loading = false,
  initialParams = {},
}) => {
  const [searchParams, setSearchParams] = useState<ContentQueryParams>({
    page: 1,
    size: 12,
    title: '',
    textContent: '',
    contentType: 'all',
    orderBy: OrderBy.CREATED_AT,
    ...initialParams,
  });

  const [showAdvanced, setShowAdvanced] = useState(false);
  const [searchText, setSearchText] = useState('');

  useEffect(() => {
    // 只在 initialParams 真正变化时更新，避免无限循环
    if (initialParams && Object.keys(initialParams).length > 0) {
      setSearchParams(prev => ({ ...prev, ...initialParams }));
    }
  }, []); // 移除 initialParams 依赖，避免循环更新

  const handleSearch = () => {
    const params: ContentQueryParams = {
      ...searchParams,
      page: 1, // 重置到第一页
    };

    // 如果有搜索文本，同时搜索标题和内容
    if (searchText.trim()) {
      params.title = searchText.trim();
      params.textContent = searchText.trim();
    } else {
      params.title = '';
      params.textContent = '';
    }

    onSearch(params);
  };

  const handleReset = () => {
    const resetParams: ContentQueryParams = {
      page: 1,
      size: 12,
      title: '',
      textContent: '',
      contentType: 'all',
      orderBy: OrderBy.CREATED_AT,
    };
    
    setSearchParams(resetParams);
    setSearchText('');
    onSearch(resetParams);
  };

  const handleParamChange = (key: keyof ContentQueryParams, value: any) => {
    setSearchParams(prev => ({
      ...prev,
      [key]: value,
    }));
  };

  const handleKeyPress = (event: React.KeyboardEvent) => {
    if (event.key === 'Enter') {
      handleSearch();
    }
  };

  const getActiveFiltersCount = () => {
    let count = 0;
    if (searchText.trim()) count++;
    if (searchParams.contentType && searchParams.contentType !== 'all') count++;
    if (searchParams.orderBy && searchParams.orderBy !== OrderBy.CREATED_AT) count++;
    return count;
  };

  const activeFiltersCount = getActiveFiltersCount();

  return (
    <Paper
      elevation={1}
      sx={{
        p: 2,
        mb: 3,
        borderRadius: 2,
      }}
    >
      {/* 主搜索区域 */}
      <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', mb: 2 }}>
        <TextField
          fullWidth
          placeholder="搜索标题或内容..."
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          onKeyPress={handleKeyPress}
          disabled={loading}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <Search color="action" />
              </InputAdornment>
            ),
            endAdornment: searchText && (
              <InputAdornment position="end">
                <IconButton
                  size="small"
                  onClick={() => setSearchText('')}
                  disabled={loading}
                >
                  <Clear />
                </IconButton>
              </InputAdornment>
            ),
          }}
          sx={{
            '& .MuiOutlinedInput-root': {
              borderRadius: 2,
            },
          }}
        />
        
        <Button
          variant="contained"
          onClick={handleSearch}
          disabled={loading}
          startIcon={<Search />}
          sx={{
            minWidth: 100,
            borderRadius: 2,
            textTransform: 'none',
          }}
        >
          搜索
        </Button>

        <Button
          variant="outlined"
          onClick={() => setShowAdvanced(!showAdvanced)}
          disabled={loading}
          startIcon={<FilterList />}
          endIcon={showAdvanced ? <ExpandLess /> : <ExpandMore />}
          sx={{
            minWidth: 'auto',
            borderRadius: 2,
            textTransform: 'none',
            position: 'relative',
            whiteSpace: 'nowrap',
          }}
        >
          筛选
          {activeFiltersCount > 0 && (
            <Chip
              label={activeFiltersCount}
              size="small"
              color="primary"
              sx={{
                position: 'absolute',
                top: -8,
                right: -8,
                minWidth: 100,
                '& .MuiChip-label': {
                  fontSize: '0.75rem',
                  px: 0.5,
                },
              }}
            />
          )}
        </Button>
      </Box>

      {/* 高级筛选区域 */}
      <Collapse in={showAdvanced}>
        <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', flexWrap: 'wrap' }}>
          <FormControl size="small" sx={{ minWidth: 120 }}>
            <InputLabel>内容类型</InputLabel>
            <Select
              value={searchParams.contentType || 'all'}
              label="内容类型"
              onChange={(e) => handleParamChange('contentType', e.target.value)}
              disabled={loading}
            >
              <MenuItem value="all">全部</MenuItem>
              <MenuItem value={ContentType.IMAGE}>图片</MenuItem>
              <MenuItem value={ContentType.VIDEO}>视频</MenuItem>
            </Select>
          </FormControl>

          <FormControl size="small" sx={{ minWidth: 120 }}>
            <InputLabel>排序方式</InputLabel>
            <Select
              value={searchParams.orderBy || OrderBy.CREATED_AT}
              label="排序方式"
              onChange={(e) => handleParamChange('orderBy', e.target.value)}
              disabled={loading}
            >
              <MenuItem value={OrderBy.CREATED_AT}>最新发布</MenuItem>
              <MenuItem value={OrderBy.LIKE_COUNT}>最多点赞</MenuItem>
            </Select>
          </FormControl>

          <Button
            variant="outlined"
            onClick={handleReset}
            disabled={loading}
            startIcon={<Clear />}
            sx={{
              borderRadius: 2,
              textTransform: 'none',
            }}
          >
            重置
          </Button>
        </Box>
      </Collapse>

      {/* 活跃筛选条件显示 */}
      {activeFiltersCount > 0 && (
        <Box sx={{ display: 'flex', gap: 1, mt: 2, flexWrap: 'wrap' }}>
          {searchText.trim() && (
            <Chip
              label={`搜索: ${searchText}`}
              onDelete={() => setSearchText('')}
              size="small"
              color="primary"
              variant="outlined"
            />
          )}
          {searchParams.contentType && searchParams.contentType !== 'all' && (
            <Chip
              label={`类型: ${searchParams.contentType === ContentType.IMAGE ? '图片' : '视频'}`}
              onDelete={() => handleParamChange('contentType', 'all')}
              size="small"
              color="primary"
              variant="outlined"
            />
          )}
          {searchParams.orderBy && searchParams.orderBy !== OrderBy.CREATED_AT && (
            <Chip
              label={`排序: ${searchParams.orderBy === OrderBy.LIKE_COUNT ? '最多点赞' : '最新发布'}`}
              onDelete={() => handleParamChange('orderBy', OrderBy.CREATED_AT)}
              size="small"
              color="primary"
              variant="outlined"
            />
          )}
        </Box>
      )}
    </Paper>
  );
};

export default SearchFilter; 